package com.zyk.scaffold.components.password;

import com.zyk.scaffold.common.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.security.NoSuchAlgorithmException;

@Slf4j
public class PasswordEncoderComponent {
    private static final String ENCODER_SPLIT = "$#&";

    public String encode(String pwd, String random) throws NoSuchAlgorithmException {
        if(StringUtils.isEmpty(pwd)) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }
        String encodeStr;
        if(StringUtils.isNotEmpty(random)) {
            encodeStr = MD5Util.computeMD5(pwd + ENCODER_SPLIT + random);
        } else {
            encodeStr = MD5Util.computeMD5(pwd);
        }
        return encodeStr;
    }

    public boolean matches(String pwd, String encodedPassword, String random) throws NoSuchAlgorithmException {
        if(StringUtils.isEmpty(pwd)) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }
        if(StringUtils.isEmpty(encodedPassword)) {
            log.warn("Empty encoded password");
            return false;
        }
        if(StringUtils.isNotEmpty(random)){
            encodedPassword =encode(encodedPassword, random);
        }
        return StringUtils.equals(pwd, encodedPassword);
    }
}